package com.lianyi.commonsdk.util.security;

import android.util.Base64;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;


public class RSAEncryptor {
	public String privateKeyPath = "";// "/Users/Isaacs/Desktop/RSA_KEYS/rsa_public_key.pem";
	public String publicKeyPath = "";// "/Users/Isaacs/Desktop/RSA_KEYS/pkcs8_private_key.pem";
	public String IosPublicKeyPath = "";

 
 
	/**
	 * @param content
	 * @param RSA_PUBLICE
	 */


	
	public static String encryptByPublic(String content, String RSA_PUBLICE) {
        try {
            PublicKey pubkey = getPublicKeyFromX509("RSA", RSA_PUBLICE);
 
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pubkey);
 
            byte plaintext[] = content.getBytes("UTF-8");
            byte[] output = cipher.doFinal(plaintext);
 
            String s = new String(Base64.encode(output, Base64.DEFAULT));
 
            return s;
 
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


	 /**
     * 得到公钥
     * @param algorithm
     * @param bysKey
     * @return
     */
    private static PublicKey getPublicKeyFromX509(String algorithm,
                                                  String bysKey) throws NoSuchAlgorithmException, Exception {
        byte[] decodedKey = Base64.decode(bysKey, Base64.DEFAULT);
        X509EncodedKeySpec x509 = new X509EncodedKeySpec(decodedKey);
 
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        return keyFactory.generatePublic(x509);
    }

	

}
